package br.com.condominio.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.condominio.entity.Responsavel;

@Repository("responsavelDao")
public class ResponsavelDAO {

	private static final Log log = LogFactory.getLog(ResponsavelDAO.class);

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public Responsavel persist(Responsavel transientInstance) {
		log.debug("persisting Responsavel instance");
		try {
			entityManager.persist(transientInstance);
			log.debug("persist successful");
			return transientInstance;
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	@Transactional
	public void remove(Responsavel persistentInstance) {
		log.debug("removing Responsavel instance");
		try {
			entityManager.remove(persistentInstance);
			log.debug("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	@Transactional
	public Responsavel merge(Responsavel detachedInstance) {
		log.debug("merging Responsavel instance");
		try {
			Responsavel result = entityManager.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	@Transactional
	public Responsavel findById(Integer id) {
		log.debug("getting Responsavel instance with id: " + id);
		try {
			Responsavel instance = entityManager.find(Responsavel.class, id);
			log.debug("get successful");
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Responsavel> findAll() {
		String jpql = " SELECT o FROM Responsavel o ORDER BY o.bloco.residencial.resNome, o.bloco.bloDescricao, o.pessoa.pessoNome";
		Query query = entityManager.createQuery(jpql);
		List<Responsavel> Responsavels = (List<Responsavel>) query
				.getResultList();
		return Responsavels;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Responsavel> findByName(String nomeResponsavel) {
		String jpql = " SELECT o from Responsavel o where (upper(o.pessoa.pessoNome) LIKE upper(:string)) ORDER BY o.bloco.residencial.resNome, o.bloco.bloDescricao, o.pessoa.pessoNome";
		Query query = entityManager.createQuery(jpql);
		query.setParameter("string", "%" + nomeResponsavel + "%");
		List<Responsavel> Responsavels = (List<Responsavel>) query
				.getResultList();
		return Responsavels;
	}
}
